package tingshu.servlet.track;

import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import tingshu.service.TrackService;
import tingshu.util.Log;
import tingshu.view_object.StudioTrackListView;
import tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/studio/track/list.json")
public class ListJsonServlet extends HttpServlet {
    private final TrackService trackService = new TrackService();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        StudioTrackListView resultView = new StudioTrackListView();

        int page = 0;
        String pageStr = req.getParameter("page");
        if (pageStr == null || pageStr.trim().isEmpty()) {
            Log.println("请求参数中没有携带页码信息，默认成第 1 页");
            page = 1;
        } else {
            pageStr = pageStr.trim();
            try {
                page = Integer.parseInt(pageStr);
            } catch (NumberFormatException exc) {
                Log.println("请求参数中没有携带页码信息，不是数字，默认成第 1 页");
                page = 1;
            }
        }

        UserVO currentUser = null;
        HttpSession session = req.getSession(false);
        if (session != null) {
            currentUser = (UserVO) session.getAttribute("currentUser");
        }
        if (currentUser == null) {
            Log.println("用户未登陆");
            resultView.currentUser = null;
            resultView.trackList = null;
        } else {
            Log.println("用户已登陆");
            resultView = trackService.listOfUser(currentUser,page);
        }

        Log.println("准备 JSON 序列化的对象是: " + resultView);
        //这一步可以不用写
        objectMapper.setDefaultPrettyPrinter(new DefaultPrettyPrinter());
        String json = objectMapper.writeValueAsString(resultView);
        Log.println("JSON 序列化后的结果是: " + json);

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        Log.println("将JSON写入响应体中");
        writer.println(json);
    }
}
